package org.leetcode.middle.leetcode75;

public class Solution {
    public void sortColors2(int[] nums) {
        int len = nums.length;
        if (len < 2) {
            return;
        }

        int zero = 0;
        int two =len;
        int i =0;

        while (i<two) {
            if (nums[i]==0) {
                swap(nums,zero,i);
                zero++;
                i++;
            }else if (nums[i]==1){
                i++;
            }else {
                two--;
                swap(nums,two,i);
            }
        }

    }
    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }



    public void sortColors(int[] nums) {

        int n = nums.length;
        if (n<2)
        {
            return;
        }

        int slow =0;
        int fast = n-1;

        for (int i = 0; i <=fast; i++) {
            if (nums[i]==0) {
                nums[i]=nums[slow];
                nums[slow]=0;
                slow++;
            }

            if (nums[i]==2)
            {
                nums[i]=nums[fast];
                nums[fast]=2;
                fast--;
                if (nums[i] != 1) {
                    i--;
                }
            }
        }

    }

    public static void main(String[] args) {
        int [] test = {0,1,2,0,2,2};

        Solution solution = new Solution();
        solution.sortColors2(test);
    }
}
